package controller

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"hanyun-admin/src/service"
	"hanyun-admin/src/utils"
	"log"
	"net/http"
)

type Login struct {
	UserName string `json:"username"`
	Password string `json:"password"`
	Code     string `json:"code"`
	Uuid     string `json:"uuid"`
}

//登录
func LoginController(c *gin.Context) {
	//定义结构体接收数据
	var login Login
	c.BindJSON(&login)
	//效验验证码
	err := CaptchaVerifyHandle(login.Uuid, login.Code)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "验证码错误！",
		})
		return //这里return只是为了断言
	}
	//调用接口
	user := service.SelectUserByUserNameAndPassword(login.UserName)
	if user.IsEmpty() {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名密码错误",
		})
		return
	}
	//效验密码是否正确
	result := utils.PasswordVerification(login.Password, user.Password)
	if result == false {
		c.JSON(http.StatusOK, gin.H{
			"code": http.StatusInternalServerError,
			"msg":  "用户名密码错误",
		})
		return
	}
	//把结构体转成json
	b, err := json.Marshal(user)
	if err != nil {
		log.Println("struct to json error", err)
	}
	//把当前用户信息存进redis
	eros := utils.InsertRedis("getLoginUser_"+login.UserName, string(b))
	if eros != nil {
		log.Println("insert redis error", eros)
	}
	token := utils.CreateJsonWebToken(login.UserName)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "登录成功！",
		"token": token,
	})
}

//获取当前用户信息
func GetLoginUserInfo(c *gin.Context) {
	//从header中获取到token
	token := c.Request.Header.Get("Authorization")
	if token != "" || len(token) != 0 {
		user := utils.GetLoginUser(token)
		//角色集合
		role := service.GetRolePermission(user)
		//菜单
		menu := service.GetMenuPermission(user)
		c.JSON(200, gin.H{
			"code":        200,
			"msg":         "操作成功",
			"permissions": menu,
			"roles":       role,
			"user":        user,
		})
	}
}

//获取路由信息
func GetRouters(c *gin.Context) {
	token := c.Request.Header.Get("Authorization")
	if token != "" || len(token) != 0 {
		//用户信息
		//user := utils.GetLoginUser(token)
		menu := service.SelectMenuTreeAll()
		data := service.BuildData(menu)
		result := service.MakeTreeCore(0, data)
		service.ArraySort(result)
		array := service.BuildMenus(result)
		fmt.Println(array)
		c.JSON(200, gin.H{
			"code": 200,
			"data": array,
			"msg":  "操作成功",
		})
	}
}

//退出登录
func Logout(c *gin.Context) {
	token := c.Request.Header.Get("Authorization")
	//获取用户的唯一标识
	jsonStr := utils.GetLoginUserName(token)
	userMap := utils.JsonToMap(jsonStr)
	//从redis中删除
	err := utils.DelRedisKey("loginUser_" + userMap["userName"].(string))
	err = utils.DelRedisKey("getLoginUser_" + userMap["userName"].(string))
	if err == nil {
		c.JSON(http.StatusOK, gin.H{
			"code": http.StatusOK,
			"msg":  "退出成功",
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code": http.StatusInternalServerError,
			"msg":  "退出失败",
		})
	}
}
